import 'package:flutter/material.dart';
import 'dart:async';
import '../models/product.dart';
import '../services/audio_manager.dart';
import '../services/api_service.dart';
import '../models/generated_content.dart';
import 'package:audioplayers/audioplayers.dart';

class LiveStreamPage extends StatefulWidget {
  final Product product;

  const LiveStreamPage({Key? key, required this.product}) : super(key: key);

  @override
  State<LiveStreamPage> createState() => _LiveStreamPageState();
}

class _LiveStreamPageState extends State<LiveStreamPage> {
  final AudioManager _audioManager = AudioManager();
  final AudioPlayer _audioPlayer = AudioPlayer();
  
  int currentIndex = 0;
  bool isPlaying = false;
  bool isLoadingDescription = false;
  String? productDescription;
  Timer? playTimer;
  Timer? countdownTimer;
  int totalPlayedSeconds = 0;
  int currentScriptSeconds = 0;
  AudioItem? currentAudioItem;
  List<AudioItem> displayItems = [];

  @override
  void initState() {
    super.initState();
    _audioManager.init(productId: widget.product.id);
    _loadDisplayItems();
    _loadProductDescription();
    
    _audioManager.bufferStream.listen((_) {
      if (mounted) {
        _loadDisplayItems();
      }
    });
  }

  @override
  void dispose() {
    playTimer?.cancel();
    countdownTimer?.cancel();
    _audioPlayer.dispose();
    _audioManager.dispose();
    super.dispose();
  }

  void _loadDisplayItems() {
    setState(() {
      displayItems = _audioManager.peekBuffer();
    });
  }

  Future<void> _loadProductDescription() async {
    print('[LiveStreamPage] 开始加载商品描述, 商品ID: ${widget.product.id}');
    setState(() {
      isLoadingDescription = true;
    });

    try {
      final description = await ApiService.getProductDescription(widget.product.id);
      print('[LiveStreamPage] 商品描述加载成功，长度: ${description.length}');
      setState(() {
        productDescription = description;
        isLoadingDescription = false;
      });
      
      // 创建推广内容
      if (productDescription != null && productDescription!.isNotEmpty) {
        print('[LiveStreamPage] 创建推广内容并添加到音频管理器');
        final content = GeneratedContent(
          id: DateTime.now().millisecondsSinceEpoch.toString(),
          text: productDescription!,
          createdAt: DateTime.now(),
        );
        _audioManager.addContent(content);
      }
    } catch (e) {
      print('[LiveStreamPage] 加载商品描述失败: $e');
      if (mounted) {
        setState(() {
          isLoadingDescription = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('获取商品推广词失败: $e')),
        );
      }
    }
  }

  void startPlay() async {
    print('[LiveStreamPage] 开始播放，缓冲状态: hasAudio=${_audioManager.hasAudio}, isLoadingDescription=$isLoadingDescription');
    if (_audioManager.hasAudio || isLoadingDescription) {
      setState(() {
        isPlaying = true;
        currentScriptSeconds = 0;
      });

      countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        setState(() {
          totalPlayedSeconds++;
        });
      });

      playNext();
    } else {
      print('[LiveStreamPage] 无可播放内容');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('暂无可播放的内容')),
      );
    }
  }

  void stopPlay() {
    setState(() {
      isPlaying = false;
    });
    playTimer?.cancel();
    countdownTimer?.cancel();
    _audioPlayer.stop();
  }

  void playNext() async {
    if (!isPlaying) {
      print('[LiveStreamPage] playNext 被调用但 isPlaying=false，退出');
      return;
    }

    final audioItem = _audioManager.getNextAudio();
    if (audioItem == null) {
      print('[LiveStreamPage] 暂无可播放音频，1秒后重试');
      Timer(const Duration(seconds: 1), () {
        if (isPlaying) playNext();
      });
      return;
    }

    print('[LiveStreamPage] 获取到新音频，序号: $currentIndex, 时长: ${audioItem.duration.inSeconds}秒');
    setState(() {
      currentAudioItem = audioItem;
      currentScriptSeconds = 0;
      currentIndex++;
    });

    try {
      print('[LiveStreamPage] 开始播放音频: ${audioItem.audioUrl}');
      await _audioPlayer.play(UrlSource(audioItem.audioUrl));
      
      playTimer?.cancel();
      playTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        setState(() {
          currentScriptSeconds++;
        });

        if (currentScriptSeconds >= audioItem.duration.inSeconds) {
          print('[LiveStreamPage] 音频播放完成，准备播放下一个');
          timer.cancel();
          if (isPlaying) {
            playNext();
          }
        }
      });
    } catch (e) {
      print('[LiveStreamPage] 播放音频失败: $e');
      if (isPlaying) {
        Timer(const Duration(seconds: 1), playNext);
      }
    }
  }

  String formatDuration(int seconds) {
    int minutes = seconds ~/ 60;
    int remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            color: Colors.black87,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  '总时长：${formatDuration(totalPlayedSeconds)}',
                  style: const TextStyle(fontSize: 16, color: Colors.white),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.cloud_download, color: Colors.white70, size: 20),
                const SizedBox(width: 8),
                Text(
                  '语音缓冲: ${_audioManager.bufferCount}/3',
                  style: const TextStyle(color: Colors.white70),
                ),
                if (isLoadingDescription) ...[
                  const SizedBox(width: 16),
                  const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white70),
                    ),
                  ),
                  const SizedBox(width: 8),
                  const Text(
                    '正在加载推广词...',
                    style: TextStyle(color: Colors.white70),
                  ),
                ],
              ],
            ),
          ),
          Expanded(
            child: Container(
              padding: const EdgeInsets.all(20),
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (currentAudioItem != null) ...[
                      Container(
                        margin: const EdgeInsets.symmetric(vertical: 8),
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: Theme.of(context).primaryColor,
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(
                            color: Theme.of(context).primaryColor,
                            width: 2,
                          ),
                        ),
                        child: Column(
                          children: [
                            Text(
                              currentAudioItem!.content.text,
                              style: const TextStyle(
                                fontSize: 20,
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                height: 1.5,
                              ),
                              textAlign: TextAlign.center,
                            ),
                            const SizedBox(height: 10),
                            LinearProgressIndicator(
                              value: currentScriptSeconds / currentAudioItem!.duration.inSeconds,
                              backgroundColor: Colors.grey[700],
                              valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                            const SizedBox(height: 5),
                            Text(
                              '${currentScriptSeconds}s / ${currentAudioItem!.duration.inSeconds}s',
                              style: const TextStyle(color: Colors.white70, fontSize: 14),
                            ),
                          ],
                        ),
                      ),
                    ],
                    
                    ...displayItems.map((item) {
                      return Container(
                        margin: const EdgeInsets.symmetric(vertical: 8),
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: Colors.grey[900],
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Column(
                          children: [
                            Text(
                              item.content.text,
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.grey[400],
                                height: 1.5,
                              ),
                              textAlign: TextAlign.center,
                            ),
                            const SizedBox(height: 5),
                            Text(
                              '时长: ${item.duration.inSeconds}秒',
                              style: const TextStyle(color: Colors.grey, fontSize: 12),
                            ),
                          ],
                        ),
                      );
                    }),
                  ],
                ),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton.icon(
                  onPressed: isPlaying ? stopPlay : startPlay,
                  icon: Icon(isPlaying ? Icons.stop : Icons.play_arrow),
                  label: Text(isPlaying ? '停止' : '开始直播'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: isPlaying ? Colors.red : Theme.of(context).primaryColor,
                    padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
                    textStyle: const TextStyle(fontSize: 18),
                  ),
                ),
                if (productDescription != null && !isPlaying) ...[
                  const SizedBox(width: 16),
                  ElevatedButton.icon(
                    onPressed: _loadProductDescription,
                    icon: const Icon(Icons.refresh),
                    label: const Text('刷新推广词'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey[800],
                      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
                    ),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }
}